<?php

namespace Beerus\Modules\DesignerAuth\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\cache\Queue;
use Doraemon\model\Designer\DesignerAuditLog;
use Doraemon\model\Designer\DesignerOpLog;
use Doraemon\model\DesignerAuth;
use Doraemon\service\Designer\AuthService;
use Doraemon\service\Designer\DesignerDingTalkAlert;
use Doraemon\service\DingTalkAlert;
use Doraemon\service\User;
use Doraemon\service\WechatAlert;
use Doraemon\tools\HhzEnv;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class CaseAuditController extends Controller
{
	public function __construct()
	{
		parent::__construct();
		Admin::script('$(".pjax-container").attr("id","pjax-container");');
	}

	// 案例审核弹框页面
	public function rejectLayer($uid)
	{
		$reject_reasons = [
			'',
			'整屋案例不符合规范',
			'效果图',
			'非家装（样板间、民宿、工装、自宅等）',
			'疑似盗图',
			'作品不足（至少需上传至少2件作品）'
		];

		$auth_info = DesignerAuth::getByUId($uid);

		return view('DesignerAuth::audit.case_reject', [
			'uid' => $uid,
			'reject_reasons' => $reject_reasons,
			'remark' => $auth_info['remark'],
			'reason2' => $auth_info['reason2']
		]);
	}

	// 案例审核不通过
	public function reject(Request $request)
	{
		$params = $request->all();
		$uid = $params['uid'];
		$admin_name = Admin::user()->username;

		$reason2 = $params['reason2'];
		if (empty($reason2)) {
			return response()->json(['msg' => '操作失败，请选择审核不通过的原因', 'code' => 0]);
		}

		$update_data = [
			'reason2' => $reason2,
			'remark' => $params['remark'],
			'house_article_audit_status' => DesignerAuth::STATUS_AUDIT_FAIL,
			'admin_id' => Admin::user()->id,
			'admin_name' => $admin_name,
			'operate_time' => time(),
		];

		$auth_info = DesignerAuth::getByUId($uid);
		$audit_log = DesignerAuditLog::getByCondition([
			'AND' => [
				'uid' => $uid,
				'audit_type' => DesignerAuditLog::AUDIT_TYPE_CASE,
			],
			'ORDER' => ['add_time' => 'DESC'],
		]);

		// 检查是否是认证期内改身份
		if ($auth_info['auth_status'] == DesignerAuth::STATUS_AUTH_COMPLETE && $audit_log['designer_type'] != $auth_info['designer_type']
			&& HhzEnv::isProduction() && !in_array(Admin::user()->username, AuthService::OPERATOR)) {
			return response()->json(['msg' => '抱歉，认证期内改身份，你没有权限操作，请联系运营', 'code' => 0]);
		}

		DesignerAuditLog::updateInfo($audit_log['id'], [
			'audit_status' => DesignerAuditLog::AUDIT_STATUS_FAIL,
			'reason' => $reason2,
			'edit_time' => time(),
			'admin_id' => Admin::user()->id,
		]);

		$res = DesignerAuth::updateInfo($params['uid'], $update_data);

		if (empty($res)) {
			return response()->json(['msg' => '操作失败，请稍后再尝试', 'code' => 0]);
		} else {
			// 记录审核操作日志
			$id = DesignerOpLog::create([
				'uid' => $uid,
				'op' => DesignerOpLog::ARTICLE_AUDIT_FAIL,
				'reason' => $reason2,
				'op_time' => date('Y-m-d H:i:s'),
				'admin_id' => Admin::user()->id,
				'admin_name' => $admin_name
			]);

			if ($id) {
				$msg = implode("\n", [
					"操作：案例审核不通过",
					"设计师uid：{$uid}",
					"不通过的原因：{$reason2}",
					"操作人：{$admin_name}\n",
				]);
                DesignerDingTalkAlert::sendBeerusDesignerAuthAuditMsg2Operator($uid, $msg);

				Queue::insertQueue('queue/Sysmsg/Send', [
					'msgCode' => 0,
					'to_uid' => $uid,
					'msgParams' => [
						'from_uid' => User::DEFAULT_HAOHAOZHU_UID,
						'title' => '',
						'detail' => '很遗憾，你的作品因为「'. $reason2 .'」没有通过审核，请重新上传案例'
					]
				], Queue::QUEUE_DORAEMON);
			}

			return response()->json(['msg' => '操作成功', 'code' => 1]);
		}
	}


	// 案例审核通过
	public function pass($uid)
	{
		if (!Admin::user()->can('designer.auth.case_audit_pass')) {
			$title = '您没有权限操作';
			$error = new MessageBag([
				'title' => $title
			]);

			return back()->with(compact('error'));
		}

		$auth_info = DesignerAuth::getByUId($uid);

		$update_data = [
			'house_article_audit_status' => DesignerAuth::STATUS_AUDIT_PASS,
			'admin_id' => Admin::user()->id,
			'admin_name' => Admin::user()->username,
			'operate_time' => time(),
		];

		$audit_log = DesignerAuditLog::getByCondition([
			'AND' => [
				'uid' => $uid,
				'audit_type' => DesignerAuditLog::AUDIT_TYPE_CASE,
			],
			'ORDER' => ['add_time' => 'DESC'],
		]);

		// 检查是否是认证期内改身份
		if ($auth_info['auth_status'] == DesignerAuth::STATUS_AUTH_COMPLETE && $audit_log['designer_type'] != $auth_info['designer_type']
			&& HhzEnv::isProduction() && !in_array(Admin::user()->username, AuthService::OPERATOR)) {
			$error = new MessageBag([
				'title' => '抱歉，认证期内改身份，你没有权限操作，请联系运营'
			]);
			return back()->with(compact('error'));
		}

		$res = DesignerAuth::update($update_data, [
			'uid' => $uid
		]);

		if (empty($res)) {
			$error = new MessageBag([
				'title' => '操作失败，请稍后再试！'
			]);

			return back()->with(compact('error'));
		} else {
			$msg = '哈喽，你的作品已经通过审核！仅需最后一步：上传身份资料，即可完成认证！（如已上传，请忽略）';

			// 认证资料资料已通过
			$identity_info_audit_status = (int)$auth_info['identity_info_audit_status'];
			if ($identity_info_audit_status == DesignerAuth::STATUS_AUDIT_PASS) {
				$msg = '你的申请资料成功通过审核，电脑登录好好住官网www.haohaozhu.com完成支付吧！';
			}

			Queue::insertQueue('queue/Sysmsg/Send', [
				'msgCode' => 0,
				'to_uid' => $uid,
				'msgParams' => [
					'from_uid' => User::DEFAULT_HAOHAOZHU_UID,
					'title' => '',
					'detail' => $msg
				]
			], Queue::QUEUE_DORAEMON);

			// 更新案例审核记录为已通过
			DesignerAuditLog::updateInfo($audit_log['id'], [
				'audit_status' => DesignerAuditLog::AUDIT_STATUS_PASS,
				'edit_time' => time(),
				'admin_id' => Admin::user()->id,
			]);

			// 记录操作日志
			$admin_name = Admin::user()->username;
			$id = DesignerOpLog::create([
				'uid' => $uid,
				'reason' => '案例通过审核',
				'op' => DesignerOpLog::ARTICLE_AUDIT_PASS,
				'op_time' => date('Y-m-d H:i:s'),
				'admin_id' => Admin::user()->id,
				'admin_name' => $admin_name
			]);

			if ($id) {
				$msg = implode("\n", [
					"操作：案例审核通过",
					"设计师uid：{$uid}",
					"操作人：{$admin_name}\n",
				]);
				DesignerDingTalkAlert::sendBeerusDesignerAuthAuditMsg2Operator($uid, $msg);
			}

			$success = new MessageBag([
				'title' => '操作成功'
			]);
			return back()->with(compact('success'));
		}
	}
}
